package com.csiec.clock.model;

import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.csiec.clock.bean.UserInfo;
import com.csiec.clock.bean.clock.BackData;
import com.csiec.clock.bean.myJoinClock.ResultCode;
import com.csiec.clock.callback.ClockCallBack;
import com.csiec.clock.callback.JoinCallBack;
import com.csiec.clock.callback.MyJoinClockCallBack;
import com.csiec.clock.utils.Constant;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class JoinModel {

    private final String www = Constant.www;
    private final String addClockInUrl = "/student/addclockin";
    private final String getPunchUrl = "/student/getpunch";

    //加入打卡的网络请求
    public void addClockIn(final String code, final JoinCallBack callBack) {
        new Thread(() -> {
            try {
                OkHttpClient client = new OkHttpClient();//新建一个OKHttp的对象
                RequestBody body = new FormBody.Builder()
                        .add("code", code)
                        .build();
                Request request = new Request.Builder()
                        .addHeader("token", UserInfo.getUserInfo().getToken())
                        .url(www + addClockInUrl)
                        .post(body)
                        .build();//创建一个Request对象

                Response response = client.newCall(request).execute();//发送请求获取返回数据
                String responseData = response.body().string();//处理返回的数据

                Log.d("JoinModel", "addClockIn: " + responseData);
                BackData backData = JSONObject.parseObject(responseData, BackData.class);

                callBack.onSuccess(backData);

            } catch (Exception e) {
                callBack.onFailed();
                e.printStackTrace();
            }
        }).start();
    }

    //获取自己参与的打卡的网络请求
    public void getPunchUrl(final MyJoinClockCallBack callBack) {
        new Thread(() -> {
            try {
                OkHttpClient client = new OkHttpClient();//新建一个OKHttp的对象
                RequestBody body = new FormBody.Builder()
                        .build();
                Request request = new Request.Builder()
                        .addHeader("token", UserInfo.getUserInfo().getToken())
                        .url(www + getPunchUrl)
                        .post(body)
                        .build();//创建一个Request对象

                Response response = client.newCall(request).execute();//发送请求获取返回数据
                String responseData = response.body().string();//处理返回的数据

                Log.d("JoinModel", "getPunchUrl: " + responseData);
                ResultCode backData = JSONObject.parseObject(responseData, ResultCode.class);

                callBack.onSuccess(backData);

            } catch (Exception e) {
                callBack.onFailed();
                e.printStackTrace();
            }
        }).start();
    }
}
